const mongoose = require('mongoose');

const backupSchema = mongoose.Schema(
  {
    date: {
      type: Date,
      required: true,
      default: Date.now,
    },
    type: {
      type: String,
      enum: ['auto', 'manual'],
      required: true,
    },
    fileSize: {
      type: Number, // 文件大小，单位KB
      required: true,
    },
    status: {
      type: String,
      enum: ['success', 'failed', 'in_progress'],
      default: 'in_progress',
    },
    filePath: {
      type: String,
      required: true,
      trim: true,
    },
    errorMessage: {
      type: String,
      trim: true,
      default: '',
    },
    isDeleted: {
      type: Boolean,
      default: false,
    },
  },
  {
    timestamps: true,
  }
);

/**
 * 获取指定日期范围内的备份记录
 * @param {Date} startDate - 开始日期
 * @param {Date} endDate - 结束日期
 * @returns {Promise<Backup[]>}
 */
backupSchema.statics.getBackupsByDateRange = async function (startDate, endDate) {
  return this.find({
    date: {
      $gte: startDate,
      $lte: endDate || new Date(),
    },
    isDeleted: false,
  }).sort({ date: -1 });
};

/**
 * 获取最近的备份记录
 * @param {number} limit - 记录条数
 * @returns {Promise<Backup[]>}
 */
backupSchema.statics.getRecentBackups = async function (limit = 10) {
  return this.find({ isDeleted: false }).sort({ date: -1 }).limit(limit);
};

/**
 * @typedef Backup
 */
const Backup = mongoose.model('Backup', backupSchema, 'backups');

module.exports = Backup;